package com.atung.parking.config.security;

import com.alibaba.fastjson.JSONObject;
import com.atung.parking.config.auth.AuthSecurityServiceImpl;
import com.atung.parking.config.auth.entity.AuthUserEntity;
import com.atung.parking.config.result.ApiResult;
import com.atung.parking.enums.AdminType;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Enumeration;

@Component
public class JwtAuthenticationTokenFilterHandler extends OncePerRequestFilter {
    private static final Logger logger = LoggerFactory.getLogger(JwtAuthenticationTokenFilterHandler.class);

    @Resource
    private AuthSecurityServiceImpl authSecurityService;
    @Resource
    private JwtTokenUtil jwtTokenUtil;
    @Resource
    private FlowConfigurationHandel flowConfiguration;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        System.out.println("Content-Type: " + request.getContentType());
        System.out.println("QueryString: " + request.getQueryString());
        System.out.println("ParameterMap: " + request.getParameterMap());

        // 包装请求
        RequestWrapper requestWrapper = new RequestWrapper(request);



        // 获取请求的完整 URL
        String requestURI = requestWrapper.getRequestURI();
        String queryString = requestWrapper.getQueryString();
        String fullURL = (queryString == null) ? requestURI : requestURI + "?" + queryString;
        logger.info("Request URL: " + fullURL);

        // 检查请求的内容类型
        String contentType = requestWrapper.getContentType();
        if ("application/json".equalsIgnoreCase(contentType)) {
            // 读取 JSON 请求体
            StringBuilder jsonBody = new StringBuilder();
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(requestWrapper.getInputStream()))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    jsonBody.append(line);
                }
            }

            // 解析 JSON 数据
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                JsonNode jsonNode = objectMapper.readTree(jsonBody.toString());
                logger.info("Parsed JSON: " + jsonNode.toPrettyString());
            } catch (IOException e) {
                logger.error("Error parsing JSON", e);
            }
        } else {
            // 获取并记录普通请求参数
            Enumeration<String> parameterNames = requestWrapper.getParameterNames();
            while (parameterNames.hasMoreElements()) {
                String paramName = parameterNames.nextElement();
                String[] paramValues = requestWrapper.getParameterValues(paramName);
                for (String paramValue : paramValues) {
                    logger.info("Parameter: " + paramName + " = " + paramValue);
                }
            }
        }

        // 继续执行后续的过滤器
        String token = request.getHeader("X-Farm-Token");
        if (!flowConfiguration.currentLimiting(WebIpUtils.getIpAddress(request), requestURI)) {
            response.setStatus(200);
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            response.getWriter().print(JSONObject.toJSONString(ApiResult.requestControl()));
            return;
        }

        // 验证当前IP是否合法
        if (StringUtils.hasText(token)) {
            Boolean tokenIp = jwtTokenUtil.validateToken(token, WebIpUtils.getIpAddress(request));
            if (!tokenIp) {
                filterChain.doFilter(requestWrapper, response);
                return;
            }
            String username = jwtTokenUtil.getUsernameFromToken(token);
            AdminType roleFromToken = jwtTokenUtil.getRoleFromToken(token);
            if (username != null && roleFromToken != null) {
                AuthUserEntity authUserEntity = null;
                if (SecurityContextHolder.getContext().getAuthentication() == null) {
                    if (roleFromToken.equals(AdminType.USER)) {
                        authUserEntity = jwtTokenUtil.getAuthUserEntity(token);
                    } else {
                        authUserEntity = authSecurityService.loadUserByUsername(username);
                    }
                    if (authUserEntity != null) {
                        UsernamePasswordAuthenticationToken authenticationToken =
                                new UsernamePasswordAuthenticationToken(authUserEntity, null, authUserEntity.getAuthorities());
                        authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                    }
                }
            }
        }
        filterChain.doFilter(requestWrapper, response);
    }
}